package com.mingtu.jgspatrol.fragment;

import static com.mingtu.jgspatrol.utils.MyConstant.ItemDecorationSpaces;
import static com.mingtu.jgspatrol.utils.MyConstant.animationType;
import static com.mingtu.jgspatrol.utils.MyConstant.isFirstOnly;
import static com.mingtu.jgspatrol.utils.MyConstant.isOpenLoadAnimation;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.base.BaseBindingFragment;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.SpacesItemDecoration;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.common.viewpager.LazyViewPager.LazyFragmentPagerAdapter;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.activity.RecordReportListActivity;
import com.mingtu.jgspatrol.adapter.RecordReportAdapter;
import com.mingtu.jgspatrol.bean.ReportRecordLeaderBean;
import com.mingtu.jgspatrol.databinding.FragmentReportRecordBinding;
import com.mingtu.jgspatrol.utils.MyConstant;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ReportRecordFragment extends BaseBindingFragment<FragmentReportRecordBinding> implements LazyFragmentPagerAdapter.Laziable {

    private int currentPage = 1;
    private boolean isLoadMore = true;
    private String beginTime = null;
    private String endTime = null;
    private List<String> userIdList = null;
    private List<ReportRecordLeaderBean.PageBean.ListBean> DataBean = new ArrayList<>();
    private RecordReportAdapter recordReportAdapter;
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    public static ReportRecordFragment getInstance() {
        ReportRecordFragment ef = new ReportRecordFragment();
        return ef;
    }

    public static ReportRecordFragment getInstance(String beginTime, String endTime) {
        ReportRecordFragment ef = new ReportRecordFragment();
        Bundle bundle = new Bundle();
        bundle.putString(ARG_PARAM1, beginTime);
        bundle.putString(ARG_PARAM2, endTime);
        ef.setArguments(bundle);
        return ef;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            beginTime = getArguments().getString(ARG_PARAM1);
            endTime = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_report_record;
    }

    @Override
    protected void initData() {
        getReportRecord(1);
    }

    @Override
    protected void initView() {
        LinearLayoutManager manager1 = new LinearLayoutManager(context);
        binding.recycler.setLayoutManager(manager1);
        binding.recycler.addItemDecoration(new SpacesItemDecoration(0, 0, ItemDecorationSpaces, ItemDecorationSpaces, ItemDecorationSpaces));

        recordReportAdapter = new RecordReportAdapter();
        if (isOpenLoadAnimation) {
            recordReportAdapter.isFirstOnly(isFirstOnly);
            recordReportAdapter.openLoadAnimation(animationType);
        }
        recordReportAdapter.setEmptyView(new EmptyDataLayout(context));
        binding.recycler.setAdapter(recordReportAdapter);
        recordReportAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                List<ReportRecordLeaderBean.PageBean.ListBean> listBeans = recordReportAdapter.getData();
                ReportRecordLeaderBean.PageBean.ListBean listBean = listBeans.get(i);
                String name = listBean.getName();
                String userId = listBean.getUserId();

                Bundle bundle = new Bundle();
                bundle.putString("name", name);
                bundle.putString("userId", userId);
                IntentUtils.getInstance().readyGo(getActivity(), RecordReportListActivity.class, bundle);
            }
        });


        //上报事件列表
//        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
//        binding.recycler.setLayoutManager(linearLayoutManager);
//        reportRecordLeaderAdapter = new ReportRecordLeaderAdapter(DataBean);
//        binding.recycler.setAdapter(reportRecordLeaderAdapter);
//        reportRecordLeaderAdapter.setOnItemClickListener(new ReportRecordLeaderAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(View view, int position) {
//                ReportRecordBean.PageBean.ListBean listBean = DataBean.get(position);
//                //Object implements Serializable或者继承Parcelable,list必须是ArrayList（若是List会提示错误）
//                ArrayList<Object> list = new ArrayList<Object>();
//                list.add(listBean);
//                Bundle bundle = new Bundle();
//                bundle.putSerializable("object", (Serializable) list);
//                IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), ReportRecordDetailsActivity.class, bundle);
//            }
//        });


    }

    @Override
    protected void getData() {
        initListener();
    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        binding.srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                binding.srlUp.finishRefresh(Constant.REFRESH_TIME);
                binding.srlUp.setNoMoreData(false);
                currentPage = 1;
                getReportRecord(1);
            }
        });
    }

    private void initLoadMoreListener() {
        binding.srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(DataBean, Constant.PAGE_SIZE);
                    getReportRecord(currentPage);
                }
                binding.srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }


    public void setBeginTime(String beginTime) {
        this.beginTime = beginTime;
    }

    public void setEndTime(String endTime) {
        this.endTime = endTime;
    }

    public void setUserIdList(List<String> userIdList) {
        this.userIdList = userIdList;
    }

    /**
     * 获取上报事件数据
     */
    public void getReportRecord(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        hashMap.put("userIdList", userIdList);
        hashMap.put("beginTime", beginTime);
        hashMap.put("endTime", endTime);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_EDPT_EVENT_LIST)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                ReportRecordLeaderBean reportRecordLeaderBean = new ReportRecordLeaderBean();
                                reportRecordLeaderBean = gson.fromJson(result, ReportRecordLeaderBean.class);

                                List<ReportRecordLeaderBean.PageBean.ListBean> dataBeans = reportRecordLeaderBean.getPage().getList();

                                try {
                                    if (dataBeans != null) {
                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;
                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        if (currentPage == 1) {
                                            recordReportAdapter.replaceData(dataBeans);
                                        } else {
                                            recordReportAdapter.addData(dataBeans);
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                isLoadMore = false;
                                ToastUtils.showLong(getResources().getString(com.mingtu.center.R.string.text_json_error));
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });
    }

}